package com.beilang.hotline.knowledge.manager.impl;

import java.util.*;
import java.io.File;

import com.beilang.base.codelookup.manager.CodeLookupMgr;
import com.beilang.base.pagination.PaginationHelper;
import com.beilang.base.util.CodeConstant;
import com.beilang.base.util.Constant;
import com.beilang.base.util.ReportUtil;
import com.beilang.base.util.StringUtil;
import com.beilang.hotline.knowledge.dao.KnowledgeDAO;
import com.beilang.hotline.knowledge.manager.KnowledgeMgr;
import com.beilang.hotline.knowledge.model.KnowledgeModel;
import com.beilang.hotline.knowledge.to.SearchTO;
import com.beilang.hotline.person.model.CompanyPersonModel;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WriteException;

@SuppressWarnings("unchecked")
public class KnowledgeMgrImpl implements KnowledgeMgr{

	private KnowledgeDAO knowledgeDAO;

	private CodeLookupMgr codeLookupMgr;

	public void setCodeLookupMgr(CodeLookupMgr codeLookupMgr) {
		this.codeLookupMgr = codeLookupMgr;
	}

	public void setKnowledgeDAO(KnowledgeDAO knowledgeDAO) {
		this.knowledgeDAO = knowledgeDAO;
	}

	public KnowledgeModel createKnowledge(KnowledgeModel knowledgeModel){
		return knowledgeDAO.createKnowledge(knowledgeModel);
	}

	public KnowledgeModel saveKnowledge(KnowledgeModel knowledgeModel) {
		return knowledgeDAO.saveKnowledge(knowledgeModel);
	}

	public void deleteKnowledge(Long knowledgeId){
		knowledgeDAO.deleteKnowledge(knowledgeId);
	}

	public KnowledgeModel getKnowledge(Long knowledgeId){
		KnowledgeModel knowledgeModel = knowledgeDAO.getKnowledge(knowledgeId);
        if (knowledgeModel!=null)
        {
            knowledgeModel.setSysName(codeLookupMgr.getCodeDesc(CodeConstant.SYS_NAME, knowledgeModel.getSysId().toString()));
        }
        return knowledgeModel;
	}

	public PaginationHelper getKnowledgeList(PaginationHelper helper,SearchTO searchTO){
		int count = knowledgeDAO.searchCount(searchTO);
		helper.setTotalSize(count);
		List list = knowledgeDAO.searchList(helper, searchTO);
		if(list!=null&&list.size()>0){
			List l=new ArrayList();
            for (Object obj : list) {
                KnowledgeModel knowledgeModel = (KnowledgeModel) obj;
                knowledgeModel.setSysName(codeLookupMgr.getCodeDesc(CodeConstant.SYS_NAME, knowledgeModel.getSysId().toString()));
                l.add(knowledgeModel);
            }
			helper.setList(l);
		}else{
			helper.setList(list);
		}
		return helper;
	}

    public void deleteAllSysKnowledges(Long sysId){
         knowledgeDAO.deleteAllSysKnowledges(sysId);
    }

    public byte[] genereateKnowlegesReport(SearchTO searchTO)
    {
       byte[] buf = new byte[0];
        String fileName = "";
        try {
            fileName = getRandomFileName();
            File file = new File(Constant.FILEPATH + fileName);

            jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(file);
            jxl.write.WritableSheet ws = wwb.createSheet("知识库", 0);
            writeKnowlegesExcelHeader(ws);
            List list = knowledgeDAO.searchList(searchTO);

            if (list!=null&&!list.isEmpty())
                 {
                     Iterator itor  = list.iterator();
                     int row=1;
                     while (itor.hasNext())
                     {
                         KnowledgeModel knowledgeModel = (KnowledgeModel)itor.next();
                          writeKnowlegesxcelDetail(knowledgeModel,ws,row);
                          row++;
                     }
                 }

				 formatSheet(ws);

				 wwb.write();
		         wwb.close();
                 ReportUtil reportUtil = new ReportUtil();
                 buf = reportUtil.readByteArrayOfSpecifiedFile(Constant.FILEPATH+fileName);
                 if (file.exists())
                 {
                     file.delete();
                 }
            } catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return buf;
    }
     public  void writeKnowlegesExcelHeader(jxl.write.WritableSheet ws ) {
         try {
             jxl.write.Label label1 = new jxl.write.Label(0, 0, "序号", getCell(true));
             jxl.write.Label label2 = new jxl.write.Label(1, 0, "系统名", getCell(true));
             jxl.write.Label label3 = new jxl.write.Label(2, 0, "题目", getCell(true));
             jxl.write.Label label4 = new jxl.write.Label(3, 0, "答案", getCell(true));
             jxl.write.Label label5 = new jxl.write.Label(4, 0, "创建人", getCell(true));

             ws.addCell(label1);
             ws.addCell(label2);
             ws.addCell(label3);
             ws.addCell(label4);
             ws.addCell(label5);
         } catch (WriteException e) {
             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
         }

     }
     public static void formatSheet(jxl.write.WritableSheet ws ) {
             for (int i = 0; i < 5; i++) {
                 if (i==2||i==3)
                 {
                     ws.setColumnView(i, 100);
                 }else if(i==0)
                {
                    ws.setColumnView(i, 10);
                } else
                 {
                    ws.setColumnView(i, 20);
                 }
            }
     }

    public  void writeKnowlegesxcelDetail(KnowledgeModel knowledgeModel,jxl.write.WritableSheet ws,int row) {
        try {
            jxl.write.Label label1 = new jxl.write.Label(0, row,String.valueOf(row), getCell(false));
            String systemName =codeLookupMgr.getCodeDesc(CodeConstant.SYS_NAME, knowledgeModel.getSysId().toString());
            jxl.write.Label label2 = new jxl.write.Label(1, row, StringUtil.deNull(systemName), getCell(false));
            jxl.write.Label label3 = new jxl.write.Label(2, row,StringUtil.deNull(knowledgeModel.getKnowledgeName()), getCell(false));
            jxl.write.Label label4 = new jxl.write.Label(3, row,StringUtil.deNull(knowledgeModel.getKnowledgeAnswer()), getCell(false));
            String createtor =codeLookupMgr.getCodeDesc(CodeConstant.USER_LIST, knowledgeModel.getCreateId().toString());
            jxl.write.Label label5 = new jxl.write.Label(4, row,StringUtil.deNull(StringUtil.splitString(createtor)), getCell(false));
            ws.addCell(label1);
            ws.addCell(label2);
            ws.addCell(label3);
            ws.addCell(label4);
            ws.addCell(label5);
        } catch (WriteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

     public  String getRandomFileName() {
	        Date cur = new Date();
	        Calendar cld = Calendar.getInstance();
	        cld.setTime(cur);
	        int mth = cld.get(Calendar.MONTH) + 1;
	        String nowStr = cld.get(Calendar.YEAR) + "" + mth + cld.get(Calendar.DATE) + cld.get(Calendar.HOUR) + cld.get(Calendar.MINUTE) + cld.get(Calendar.SECOND);
	        Random rdm = new Random();
	        String rdmNum = String.valueOf(rdm.nextInt());
	        return nowStr + rdmNum + Constant.EXCEL_EXTENSION;
	    }

      public WritableCellFormat getCell(boolean isBold) {

            WritableFont font=null;
          if (isBold)
          {
               font  = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD);
          }else
          {
               font  = new WritableFont(WritableFont.TIMES, 12, WritableFont.NO_BOLD);
          }


            try {
	            font.setColour(Colour.BLACK);
	        } catch (WriteException e1) {
	            e1.printStackTrace();
	        }
	        WritableCellFormat format = new WritableCellFormat(font);
	        try {
	            format.setAlignment(jxl.format.Alignment.LEFT);
	            format.setVerticalAlignment(jxl.format.VerticalAlignment.TOP);
	            format.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
	        } catch (WriteException e) {
	            e.printStackTrace();
	        }
	        return format;
	    }

}
